package com.ycg.biquge.common;

import com.ycg.biquge.exception.IpBackException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author YCG
 * @date 2024-04-30 20:35
 * @description 验证全局异常处理器
 */
@RestControllerAdvice
public class MyExceptionHandler {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result<String> handler(MethodArgumentNotValidException ex) {
        StringBuilder errMsg = new StringBuilder();
        for (ObjectError allError : ex.getAllErrors()) {
            errMsg.append("&").append(allError.getDefaultMessage());
        }
        return Result.error(errMsg.delete(0,1).toString());
    }

    @ExceptionHandler(IpBackException.class)
    public Result<String> handler(IpBackException ex) {
        return Result.error(ex.getMessage());
    }


    @ExceptionHandler(RuntimeException.class)
    public Result<String> handler(RuntimeException ex) {
        return Result.error(ex.getMessage());
    }
}
